﻿using UnityEngine;
using System.Collections;
using System.Reflection;

/// <summary>
/// Reusable Singleton Class.
/// </summary>
/// <typeparam name="T">class to use singleton</typeparam>
public static class wsSingleton<T>
       where T : class
{
    static volatile T _instance;
    static object _lock = new object();

    static wsSingleton()
    {
    }

    /// <summary>
    /// Get Instance.
    /// </summary>
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        //ConstructorInfo constructor = null;

                        //try
                        //{
                        //    // Binding flags exclude public constructors.
                        //    constructor = typeof(T).GetConstructor(BindingFlags.Instance |
                        //                  BindingFlags.NonPublic, null, new Type[0], null);
                        //}
                        //catch (Exception exception)
                        //{
                        //    throw new wsSingletonException(exception);
                        //}

                        //if (constructor == null || constructor.IsAssembly)
                        //    // Also exclude internal constructors.
                        //    throw new wsSingletonException(string.Format("A private or " +
                        //          "protected constructor is missing for '{0}'.", typeof(T).Name));

                        //_instance = (T)constructor.Invoke(null);

                        _instance = System.Activator.CreateInstance<T>();
                    }
                }
            }

            return _instance;
        }
    }
}